package com.zhangqiang.git.cloud.oauth.service;

import com.zhangqiang.git.cloud.domain.consumer.SysUser;
import com.zhangqiang.git.cloud.remote.model.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户登陆验证用户信息
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RemoteUserService remoteUserService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 查询用户服务
        SysUser user = remoteUserService.findUserByName(username);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在！");
        }else{
            // 用户角色也应在数据库中获取
            List<String> roles = remoteUserService.findRolesByUser(user.getUserId());
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            for(String role: roles){
                authorities.add(new SimpleGrantedAuthority(role));
            }
            // 线上环境应该通过用户名查询数据库获取加密后的密码
            String password = passwordEncoder.encode(user.getPassword());
            return new org.springframework.security.core.userdetails.User(username,password, authorities);
        }
    }
}
